package com.ruoyi.task;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import cn.binarywang.wx.miniapp.constant.WxMaConstants;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SysMessage;
import com.ruoyi.system.mapper.SysMessageMapper;
import com.ruoyi.system.service.ISysConfigService;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 定时任务调度测试
 * 
 * @author ruoyi
 */
@Component("msgtask")
public class MessageSendTask
{
    @Resource
    private SysMessageMapper sysMessageMapper;
    @Resource
    private WxMaService wxService;


    @Autowired
    private ISysConfigService configService;


    public void runTask()
    {
        String templateid = configService.selectConfigByKey("sys.templateid");
        if(templateid==null || templateid==""){
            throw new RuntimeException("templateid 配置失误 ");
        }
        SysMessage query = new SysMessage();
        query.setStatus("0");
        List<SysMessage>  msgs=  sysMessageMapper.selectSysMessageList(query);
        // 微信通知
        if(msgs==null || msgs.size()==0){
            return;
        }
        msgs.forEach(msg->{
         try {
             if(msg.getOpenid()!=null){
                 push(msg.getOpenid(),templateid);
                 msg.setStatus("1");
                 msg.setUpdateTime(new Date());
                 sysMessageMapper.updateSysMessage(msg);
             }
         }catch (Exception e){
            e.printStackTrace();
         }
        });


        // 短信通知
        msgs.forEach(msg->{
            try {

            }catch (Exception e){
                e.printStackTrace();
            }
        });


  }


  public void push(String openid,String templateid ) {
        WxMaSubscribeMessage message = new WxMaSubscribeMessage();
        message.setTemplateId(templateid);
        message.setToUser(openid);
        message.setLang(WxMaConstants.MiniProgramLang.ZH_CN);
        message.setMiniprogramState(WxMaConstants.MiniProgramState.FORMAL);
        message.addData(new WxMaSubscribeMessage.MsgData("thing1", "病友互助"));
        message.addData(new WxMaSubscribeMessage.MsgData("thing4", "献血地址，左贡县人民医院"));
      try {
          this.wxService.getMsgService().sendSubscribeMsg(message);
      } catch (Exception e) {
          e.printStackTrace();
      }
  }
}
